# -*- coding: utf-8 -*-
# @Time    : 2024/1/11  16:35
# @Author  : zhanghao
# @FileName: slave.py
# @Software: PyCharm
"""
    Description: 子任务
"""
from multiprocessing import Process, Pipe

from api.domain.file_result import FileResult
from domain.signal_unit import SignalUnit
from helper.file_helper import FileHelper
from helper.event_type import EventType
from core.paddle_ocr import PaddleOcr
from core.ocr_result import OcrResult
from core.rule_actuator import RuleActuator
from config.logger import Logger
from config.config import Config
from db.sqlite import Sqlite

import os
import json
import fitz
import datetime


class Worker(Process):
    logger = Logger.get()

    paddle_ocr = PaddleOcr()
    config: Config
    rule_actuator: RuleActuator

    conn: Pipe

    sqlite: Sqlite

    def __init__(self, conn: Pipe, config: Config):
        super().__init__()
        self.sqlite = Sqlite()
        self.conn = conn
        self.config = config
        self.rule_actuator = RuleActuator(config)
        self.logger.info('worker 初始化成功......')

    def run(self):
        self.logger.info(str(os.getpid()) + ' config version:' + self.config.getVersion())
        self.logger.info(str(os.getpid()) + ' worker 开始接收任务......')
        while True:
            event = self.conn.recv()
            self.logger.info(event)

            try:
                self.config.loadConfig()
                self.rule_actuator.rules = self.config.rule_config.rules
            except Exception as e:
                self.logger.exception('配置更新异常：', e)

            if event.event_type != EventType.UPDATE_CONFIG:
                task_data = event.task_info
                try:
                    self.logger.info('worker 接收到任务,编号id：' + str(task_data.id))
                    if task_data:
                        task_data = self.work(task_data)
                    self.logger.info('处理成功: '+ str(task_data.id))
                except fitz.FileNotFoundError:
                    task_data.task_status = 3
                    task_data.reason = '文件不存在'
                    self.logger.error('文件不存在：', task_data.file_link)

                except Exception as e:
                    self.logger.error('处理异常，文件：', task_data.file_link)
                    task_data.task_status = 3
                    task_data.reason = '未知异常'
                    self.logger.exception('未知异常：', e)

                finally:
                    # 任务结束-更新任务状态
                    task_data.appendInfo('execute_end_time', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    self.logger.info('处理成功: ' + str(task_data.id))
                    self.sqlite.updateTask(task_data)
                    self.logger.info('处理成功: ' + str(task_data.id) + str(task_data.task_result))

                    # event--END_PROCESS
                    event = SignalUnit.build(EventType.END_PROCESS, task_data)
                    self.conn.send(event)
                    self.logger.info('处理结束end: ' + str(task_data.id))
                    self.logger.info(event)

    def work(self, task_data: FileResult) -> FileResult:
        # event--START_PROCESS
        self.logger.info('开始处理任务' + task_data.file_link)

        # 清空缓存
        FileHelper.clearTaskCache()

        # 下载文件
        file_path = FileHelper.downloadFile(task_data.file_link)
        self.logger.info('文件下载成功：' + file_path)

        # 判断文件类型
        if FileHelper.fetchFileType(file_path) == 1:
            content = self.processPdf(file_path)
            self.logger.info('pdf识别结束:' + content.text)
            task_data = self.innerProcess(content, task_data)
        elif FileHelper.fetchFileType(file_path) == 2:
            content = self.processImg(file_path)
            task_data = self.innerProcess(content, task_data)
        else:
            task_data.task_status = 3
            task_data.reason = '不支持该文件类型'

        self.logger.info('work end：' + file_path)
        self.logger.info('work end：' + str(task_data.task_status))
        return task_data

    # 处理pdf
    def processPdf(self, file_path):
        return self.paddle_ocr.processPdf(file_path)

    # 处理图片
    def processImg(self, file_path):
        return self.paddle_ocr.processImg(file_path)

    def innerProcess(self, content: OcrResult, task_data: FileResult):
        execute_result = self.rule_actuator.processContent(content)
        self.logger.info(execute_result)

        if len(execute_result.keys()) > 0:
            task_data.task_status = 2
            task_data.task_result = json.dumps(execute_result)
        else:
            task_data.task_status = 3
            task_data.reason = '没有对应规则'

        self.logger.info(task_data.task_status)
        self.logger.info(task_data.task_result)

        return task_data
